package com.osgi.desktop.ui.plugins;

import com.onetwork.core.resource.Resource;
import com.onetwork.core.resource.ResourceType;
import com.onetwork.core.ui.components.BasicWindow;
import com.onetwork.core.ui.components.dialog.listeners.DialogListener;
import com.onetwork.core.ui.components.grid.actions.AdicionarAction;
import com.onetwork.core.ui.components.grid.actions.RemoverAction;
import com.onetwork.core.ui.components.grid.listeners.GridListener;
import com.osgi.desktop.domain.SitePlugin;
import com.osgi.desktop.domain.SiteUpdate;
import com.osgi.desktop.ui.plugins.dialog.SiteUpdateDialog;
import com.osgi.desktop.ui.plugins.model.DisponiveisPluginsTreeTableModel;
import com.osgi.desktop.ui.plugins.model.PluginsAInstalarTableModel;
import com.osgi.desktop.ui.plugins.model.PluginsInstaladosTableModel;
import com.osgi.desktop.ui.plugins.model.SiteUpdateTableModel;
import com.osgi.desktop.ui.util.SwingUtil;
import com.osgi.desktop.ui.util.UtilIcons;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
import org.knopflerfish.framework.Framework;
import org.osgi.framework.Bundle;

public class GerenciamentoDePluginsPanel extends BasicWindow implements DialogListener, GridListener, PluginsDisponiveisChangeListener {
    private PluginsAInstalarTableModel aInstalarTableModel;
    private PluginsInstaladosTableModel instaladosTableModel;   
    private DisponiveisPluginsTreeTableModel disponiveisPluginsTreeTableModel;
    private SiteUpdateTableModel siteUpdateTableModel;
    private SiteUpdateDialog siteUpdateDialog;
    private List<SiteUpdate> listaSiteUpdate;
    private DefaultMutableTreeTableNode rootNode;
    private JXTreeTable disponiveisPluginsTreeTable;
    
    public GerenciamentoDePluginsPanel() {
        this.setName("Gerenciamento de plugins");
    }
    
    @Override
    protected void initialize() {        
        this.aInstalarTableModel = new PluginsAInstalarTableModel();
        this.instaladosTableModel = new PluginsInstaladosTableModel();
        this.siteUpdateTableModel  = new SiteUpdateTableModel();
        this.siteUpdateDialog = new SiteUpdateDialog(this);  
        this.rootNode = new DefaultMutableTreeTableNode();        
        this.disponiveisPluginsTreeTableModel = new DisponiveisPluginsTreeTableModel(this.rootNode);
        initComponents();       
        this.siteUpdateTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int row = siteUpdateTable.getSelectedRow();
                    if (row > -1) {                       
                        SiteUpdate siteUpdate = siteUpdateTableModel.getObjectSelected(row);
                        siteUpdateDialog.setVisible(true,siteUpdate);                           
                    }                    
                }
            }
            @Override
            public void mousePressed(MouseEvent e) {}
            @Override
            public void mouseReleased(MouseEvent e) {}
            @Override
            public void mouseEntered(MouseEvent e) {}
            @Override
            public void mouseExited(MouseEvent e) {}
        });
        this.mainToolBar.add(new AdicionarAction(this)); 
        this.mainToolBar.add(new RemoverAction(this));
        this.disponiveisPluginsPanel.desativarButtonVisible(false);        
        disponiveisPluginsTreeTable = new JXTreeTable(this.disponiveisPluginsTreeTableModel);
        disponiveisPluginsTreeTable.addMouseListener(new InstalarPluginsListener(this.disponiveisPluginsPanel));
        disponiveisPluginsTreeTable.setTreeCellRenderer(new PluginsDisponiveisTreeCellRenderer());
        this.disponiveisPluginsPanel.setTable(disponiveisPluginsTreeTable);
        this.disponiveisPluginsPanel.addPluginsDisponiveisChangeListener(this);
        JXTable instaladosTable = new JXTable(this.instaladosTableModel);
        instaladosTable.addMouseListener(new GerenciarPluginsListener(this.instaladosPluginsPanel));        
        this.instaladosPluginsPanel.setTable(instaladosTable);
        this.mainTabbedPane.setIconAt(0, UtilIcons.pluginsDisponiveisIcon());
        this.mainTabbedPane.setIconAt(1, UtilIcons.pluginsInstaladosIcon());
        this.mainTabbedPane.setIconAt(2, UtilIcons.pluginsSiteUpdateIcon());
        this.pesquisar();
    }
    
    @Override
    public URL createImage() {
        return GerenciamentoDePluginsPanel.class.getResource("/imagens/package.png");
    }

    @Override
    protected void configurePanels() {}

    @Override
    public void imprimir() {}

    @Override
    public void salvar() {}

    @Override
    public void cancelar() {}

    @Override
    public void excluir() {}

    @Override
    public void novo() {}

    @Override
    public void pesquisar() {
        this.instaladosTableModel.clear();
        Framework framework = Resource.get(ResourceType.OSGIFramework);
        Bundle[] bundles = framework.getSystemBundleContext().getBundles();
        for (Bundle bundle : bundles) {
            if (bundle.getBundleId() != 0) this.instaladosTableModel.addObject(bundle);
        }
        
        listaSiteUpdate = SiteUpdate.findAll(SiteUpdate.class);
        this.siteUpdateTableModel.addObjects(listaSiteUpdate);
        this.siteUpdateTable.updateUI();
        readDefaultMutableTreeTableNodes();
    }
    
    public void readDefaultMutableTreeTableNodes(){ 
        Framework framework = Resource.get(ResourceType.OSGIFramework);
        this.rootNode = new DefaultMutableTreeTableNode();     
        for (SiteUpdate siteUpdate : listaSiteUpdate) {
            DefaultMutableTreeTableNode newSiteUpdateNode = new DefaultMutableTreeTableNode(siteUpdate);
            try {
                List<SitePlugin> listaDoPlugins = siteUpdate.getListaDePlugins();
                for (SitePlugin sitePlugin : listaDoPlugins) {
                    long idBundle = framework.getBundleId(sitePlugin.getUrl().toString());
                    if (idBundle == -1) {
                        DefaultMutableTreeTableNode newSitePluginNode = new DefaultMutableTreeTableNode(sitePlugin);
                        newSiteUpdateNode.add(newSitePluginNode);
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(GerenciamentoDePluginsPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
            this.rootNode.add(newSiteUpdateNode);
        }
        this.disponiveisPluginsTreeTableModel.setRoot(this.rootNode);
        disponiveisPluginsTreeTable.updateUI();
        disponiveisPluginsTreeTable.expandAll();
    }
    
    @Override
    public void limpar() {}
    
    @Override
    public void dialogListenerLimpar() {}

    @Override
    public void dialogListenerPesquisar() {}

    @Override
    public void dialogListenerConfirmar() {        
        boolean isFormValid = this.siteUpdateDialog.validaForm();
        if (isFormValid) {
            SiteUpdate siteUpdate = this.siteUpdateDialog.getSiteUpdate();
            siteUpdate.save();
            this.pesquisar();
            this.siteUpdateDialog.setVisible(false);
        }
         
    }

    @Override
    public void dialogListenerCancelar() {
         this.siteUpdateDialog.setVisible(false);
    }
    
    @Override
    public void gridListenerAdicionar() {
        siteUpdateDialog.setVisible(true);
    }

    @Override
    public void gridListenerRemover() {
        int row = this.siteUpdateTable.getSelectedRow();
        if (row > -1) {
            boolean isExcluir = SwingUtil.questionYesNo("Deseja realmente excluir este item?");
            if (isExcluir) {
                SiteUpdate siteUpdate =  this.siteUpdateTableModel.getObjectSelected(row);
                siteUpdate.delete();
                this.siteUpdateTable.clearSelection();
                this.pesquisar();
            }            
        }else SwingUtil.displayWarning("Selecione o item que deseja remover.");
    }
    
    @Override
    public void notifyPluginsDisponiveisChangeListener(SitePlugin sitePlugin) {
        pesquisar();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainTabbedPane = new javax.swing.JTabbedPane();
        disponiveisPluginsPanel = new com.osgi.desktop.ui.plugins.PluginsPanel();
        instaladosPluginsPanel = new com.osgi.desktop.ui.plugins.PluginsPanel();
        siteUpdatePanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        siteUpdateTable = new javax.swing.JTable();
        mainToolBar = new javax.swing.JToolBar();

        mainTabbedPane.addTab("Disponiveis", disponiveisPluginsPanel);
        mainTabbedPane.addTab("Instalados", instaladosPluginsPanel);

        siteUpdateTable.setModel(siteUpdateTableModel);
        jScrollPane1.setViewportView(siteUpdateTable);

        mainToolBar.setFloatable(false);
        mainToolBar.setRollover(true);

        javax.swing.GroupLayout siteUpdatePanelLayout = new javax.swing.GroupLayout(siteUpdatePanel);
        siteUpdatePanel.setLayout(siteUpdatePanelLayout);
        siteUpdatePanelLayout.setHorizontalGroup(
            siteUpdatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
            .addGroup(siteUpdatePanelLayout.createSequentialGroup()
                .addGap(1, 1, 1)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE))
        );
        siteUpdatePanelLayout.setVerticalGroup(
            siteUpdatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(siteUpdatePanelLayout.createSequentialGroup()
                .addComponent(mainToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE))
        );

        mainTabbedPane.addTab("Site update", siteUpdatePanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 511, Short.MAX_VALUE)
        );

        mainTabbedPane.getAccessibleContext().setAccessibleName("Disponiveis");
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.osgi.desktop.ui.plugins.PluginsPanel disponiveisPluginsPanel;
    private com.osgi.desktop.ui.plugins.PluginsPanel instaladosPluginsPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane mainTabbedPane;
    private javax.swing.JToolBar mainToolBar;
    private javax.swing.JPanel siteUpdatePanel;
    private javax.swing.JTable siteUpdateTable;
    // End of variables declaration//GEN-END:variables
}